﻿using Framework.Timer;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
/// <summary>
/// 长按按钮
/// </summary>
public class LongPressBtn : Button, IPointerDownHandler,IPointerExitHandler,IPointerUpHandler
{

    public bool pressed;//按下
    public bool longPress;//当前是长按
    public float pressTimer = 0;//长按计时器
    public float longPressTime = 0.3f;//0.3秒算长按

    public Action longPressCallBack;//长按回调
    public Action longPressExistCallBack;//长按结束后回调
    public Action clickCallBack;//普通按回调


    /// <summary>
    /// 长按按钮初始化
    /// </summary>
    /// <param name="longPressCB">长按后方法</param>
    /// <param name="longPressExistCB">长按后离开方法</param>
    /// <param name="clickCB">单点方法</param>
    public void AddLongBtnListener(Action longPressCB,Action longPressExistCB, Action clickCB)
    {
        //Debug.Log("长按钮初始化");
        pressed = false;
        longPress = false;
        pressTimer = 0;
        longPressCallBack = longPressCB;
        longPressExistCallBack = longPressExistCB;
        clickCallBack = clickCB;
        GameUpdateMgr.Instance.AddUpdater(PressCountDown);
    }

    private void PressCountDown()
    {
        if (!pressed) return;
        //Debug.Log("计时");
        if (pressTimer < longPressTime)
        {
            pressTimer += Time.deltaTime;
        }
        else
        {
            longPress = true;
            longPressCallBack?.Invoke();
            pressed = false;
        }
    }
    
    /*/// <summary>
    /// 无法加入GameUpdateMgr
    /// </summary>
    private void Update()
    {
        if (pressed)
        {
            //Debug.Log("计时");
            if (pressTimer < longPressTime)
            {
                pressTimer += Time.deltaTime;
            }
            else
            {
                longPress = true;
                if (longPressCallBack != null)
                    longPressCallBack();
                pressed = false;
            }
        }
    }*/
    
    /// <summary>
    /// 按下
    /// </summary>
    /// <param name="eventData"></param>
    public override void OnPointerDown(PointerEventData eventData)
    {
        pressed = true;
        pressTimer = 0;
        //Debug.Log("按下");
    }
    /// <summary>
    /// 离开时
    /// </summary>
    /// <param name="eventData"></param>
    public override void OnPointerExit(PointerEventData eventData)
    {
        pressed = false;
        longPress = false;
        longPressExistCallBack?.Invoke();
    }

    public override void OnPointerUp(PointerEventData eventData)
    {
        //Debug.Log("抬起");
        if (!longPress)
        {
            if (pressed)
            {
                clickCallBack?.Invoke();
            }
        }
        else
        {
            longPressExistCallBack?.Invoke();
        }
        pressed = false;
        longPress = false;

    }
}
